package git.soulbgm.utils;

import org.apache.commons.compress.utils.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * IO操作类
 *
 * @author SoulBGM
 * @date 2018-07-17
 */
public class IoUtil {

    private static final LogHelper LOG = new LogHelper(IoUtil.class);

    /**
     * 将文件读出装入byte数组中
     *
     * @param path 文件路径
     * @return {@link byte[]}
     */
    public static byte[] toByteArray(String path) {
        FileInputStream is = null;
        try {
            File file = new File(path);
            if (file.exists()) {
                is = new FileInputStream(file);
                return IOUtils.toByteArray(is);
            }
            return null;
        } catch (IOException e) {
            LOG.error("读取" + path + "文件成byte数组失败", e);
            return null;
        } finally {
            close(is, null);
        }
    }

    /**
     * 获得文件中的内容
     *
     * @param file 文件
     * @return {@link String}
     */
    public static String getFileContent(File file) {
        if (!FileUtil.exist(file)) {
            return null;
        }
        try (FileInputStream is = new FileInputStream(file)) {
            return StringUtil.byteArrayToString(IOUtils.toByteArray(is));
        } catch (IOException e) {
            LOG.error("读取文件内容失败", e);
            return null;
        }
    }

    /**
     * 写入数据
     *
     * @param path    地址
     * @param context 内容
     */
    public static boolean writer(String path, String context) {
        FileOutputStream outputStream = null;
        try {
            boolean exist = FileUtil.exist(new File(path));
            if (!exist) {
                FileUtil.createFile(path);
            }
            outputStream = new FileOutputStream(path);
            return writer(outputStream, context);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } finally {
            close(null, outputStream);
        }
    }

    /**
     * 写入数据
     *
     * @param outputStream 输入流
     * @param context      内容
     */
    public static boolean writer(OutputStream outputStream, String context) {
        try {
            if (context != null) {
                outputStream.write(context.getBytes(StandardCharsets.UTF_8));
                return true;
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            close(null, outputStream);
        }
    }

    /**
     * 关闭输入流和输出流
     *
     * @param is 输入流
     * @param os 输出流
     */
    public synchronized static void close(InputStream is, OutputStream os) {
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        } catch (IOException e) {
            LOG.info("关闭读写流失败", e);
        }
    }
}
